package org.sintec.AndroidCarConnectivity;

import android.util.Log;

import java.io.IOException;
import java.util.Observable;

import org.sintec.AndroidCarConnectivity.Command.*;

public class ConnectivityManager extends java.util.Observable
{
	private static final String TAG = "ConnectivityManager";
	
	private CommandQueue mCommandRequestQueue = null;
    private CommandQueue mCommandResponseQueue = null;
    
    private ConnectivitySocket mSocket = null;
    private ConnectivityHttp mHttp = null;
    private ConnectivityBluetooth mBluetooth = null;
    private serviceConnectivity mOwner = null;
    
    private static String mStateSocket="";
    private static String mStateBluetooth="";
    private static String mStateHttp="";
    private static String mStatePhoneIp="";
	
	ConnectivityManager(serviceConnectivity owner)
	{
		// TODO: add some handler/context to link with activity
		mCommandRequestQueue = new CommandQueue();
		mCommandResponseQueue = new CommandQueue();
		mOwner = owner;
	}

    public boolean startAllServices(String btAddress, int socketPort, int httpPort)
    {
		if (mHttp != null)
		{
			return false;
		}
		try 
		{
			// TODO: remove hardcoded port number
			mHttp = new ConnectivityHttp(8888, null, mCommandRequestQueue, this);
		} catch (IOException e) 
		{
			e.printStackTrace();
			Log.e(TAG, e.toString());
		}
		
		if (null == mSocket)
		{
			mSocket = new ConnectivitySocket(mCommandRequestQueue, mCommandResponseQueue, this);
			mSocket.startSocketServer(socketPort);
		}
		
		if (null == mBluetooth)
		{
			mBluetooth = new ConnectivityBluetooth(mCommandRequestQueue, mCommandResponseQueue, this);
			mBluetooth.connect("00:19:5D:EE:25:A3");
		}
    	
    	return true;    // TODO: FIXME: hardocded return value
    }
    
    public boolean stopAllServices()
    {
		if (mHttp != null)
		{
			mHttp.stopHttpServer();
			mHttp = null;
		}
		
		if (mSocket != null)
		{
			mSocket.stopSocketServer();
			mSocket = null;
		}
		
		if (mBluetooth != null)
		{
			mBluetooth.stopBluetoothServer();
			mBluetooth = null;
		}
		
		return true;	// TODO: FIXME: hardocded return value
    }
    
    public void updateStateBt(String state)
    {
    	mStateBluetooth = state;
    	sendBroadcast();
    }
    public void updateStateSocket(String state)
    {
    	mStateSocket = state;
    	sendBroadcast();
    }
    public void updateStateHttp(String state)
    {
    	mStateHttp = state;
    	sendBroadcast();
    }
    public void updateStatePhoneIp(String state)
    {
    	mStatePhoneIp = state;
    	sendBroadcast();
    }
    
    private void sendBroadcast()
    {
    	mOwner.sendBroadcast(mStatePhoneIp, mStateBluetooth, mStateSocket, mStateHttp);
    }
}
